package tech.eyao.hs60x.annotation.aop;

import java.nio.file.AccessDeniedException;
import java.util.Set;

import org.apache.commons.lang3.builder.ToStringBuilder;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import tech.eyao.hs60x.annotation.Admin;
import tech.eyao.hs60x.common.ConstantsKey;
import tech.eyao.hs60x.dao.AccountRelationDao;
import tech.eyao.hs60x.exception.Hs60xException;
import tech.eyao.hs60x.utils.TokenUtils;

@Aspect
@Component
@EnableAspectJAutoProxy(proxyTargetClass = true)
public class Hs60xAop implements Aop {
    private static final Logger logger = LoggerFactory.getLogger(Hs60xAop.class);

	@Autowired
	private RedisTemplate<String, String> redisTemplate;
	@Autowired
	private AccountRelationDao accountRelationDao;
	
	@Override
	public Object getData(Object... params) {
		throw new Hs60xException("unknow exception");
	}
	
	@Before("execution(* tech.eyao.hs60x.user.controller..*.*(..)) && @annotation(annotation)")
	public void execute(JoinPoint joinpoint,Admin annotation) throws AccessDeniedException {
		if(!check()) {
			throw new Hs60xException("您无权操作！");
		}
	}

	public boolean check() {
	    try {
	        Set<String> watchSet = redisTemplate.opsForSet().members(ConstantsKey.getAdminKey(TokenUtils.getUserId()));
	        if(CollectionUtils.isEmpty(watchSet)) {
	            // DB 验证
	            if(!accountRelationDao.isAdmin(TokenUtils.getUserId())) {
	                return Boolean.FALSE;
	            }
	        }
	        logger.info("tech.eyao.hs60x.annotation.aop.Hs60xAop.check()>>>>watchSet:{}",ToStringBuilder.reflectionToString(watchSet));
        } catch (Throwable e) {
            logger.error("redisTemplate.opsForSet()>>>>",e.getMessage());
            //浪起来
            if(accountRelationDao.isAdmin(TokenUtils.getUserId())) {
                return Boolean.TRUE;
            }
        }
		return Boolean.TRUE;
	}
}
